<?php

/**
 * 字段管理
 * @copyright (c) 2013, Mr.Wang
 * 
 */
class FormAction extends AdminAction {

    public $formid, $fields, $banfie;

    function _initialize() {
        parent::_initialize();
        C('TAGLIB_BUILD_IN', "cx,tpl,admin");
        import("TagLib.TagLibTpl", APP_PATH . 'Lib');
        $this->assign("show_header", true);
        $this->formid = (int) $this->_get("formid");
        //字段类型存放目录
        $this->fields = LIB_PATH . "ORG/Fields/";
        //允许使用的字段列表
        $this->banfie = array("text", "textarea", "box", "number", "editor", "datetime", "downfiles", "image", "images", "omnipotent");
        $this->modelfield = D("Model_field");
    }

    /**
     * 删除指定Taglib
     */
    private function _removeTagLib() {
        $tagLib = "tpl";
        $array  = explode(",", C('TAGLIB_BUILD_IN'));
        $key    = array_search($tagLib, $array);
        if ($key !== false) {
            unset($array[array_search($tagLib, $array)]);
        }
        C('TAGLIB_BUILD_IN', implode(',', $array));
    }

    /**
     * 管理字段
     */
    public function index() {
        if (IS_POST) {
            foreach ($_POST['listorders'] as $id => $listorder) {
                $this->modelfield->where(array('fieldid' => $id))->save(array('listorder' => $listorder));
            }
            $this->success("排序更新成功！");
        } else {
            if (!$this->formid) {
                $this->error("缺少参数！");
            }
            $model = M("Model")->where(array("modelid" => $this->formid))->find();
            if (!$model) {
                $this->error("该表单不存在！");
            }
            //载入字段配置文件
            require $this->fields . "fields.inc.php";
            $data = D("Model_field")->Modelfield($this->formid);

            //不允许删除的字段，这些字段讲不会在字段添加处显示
            $this->assign("not_allow_fields", $not_allow_fields);
            //允许添加但必须唯一的字段
            $this->assign("unique_fields", $unique_fields);
            //禁止被禁用的字段列表
            $this->assign("forbid_fields", $forbid_fields);
            //禁止被删除的字段列表
            $this->assign("forbid_delete", $forbid_delete);
            //可以追加 JS和CSS 的字段
            $this->assign("att_css_js", $att_css_js);
            $this->assign("modelinfo", $model);
            $this->assign("data", $data);
            $this->assign("modelinfo", $model);
            $this->assign("formid", $this->formid);
            $this->display();
        }
    }

    public function getForm($_D) {
        $this->assign("_D", $_D);
        /* 加载语言包 */
        L(include $this->fields . "_From_config/lang.php");
        L(include $this->fields . "{$_D['formtype']}/tpl/lang.php");
        $this->assign("tpl_common_default", $this->fields . "_From_config/common_default.php");
        $this->assign("tpl_common_show", $this->fields . "_From_config/common_show.php");
        $content = $this->fetch($this->fields . "{$_D['formtype']}/tpl/tpl.php");
        return $content;
    }

    public function view() {
        //require_cache(RUNTIME_PATH . 'content_form.class.php');
        //实例化表单类 传入 模型ID 栏目ID 栏目数组
        //$content_form = new content_form();
        $this->display();
    }

    /**
     * 添加字段
     */
    public function add() {
        if (IS_POST) {
            $this->_removeTagLib();
            $temptext = Input::forTarea($this->getForm($_POST));
            $this->assign("temptext", $temptext);
            $this->display("Index:codeshow");
        } else {

            require $this->fields . "fields.inc.php";
            //字段类型过滤
            foreach ($fields as $_k => $_v) {
                if (in_array($_k, $not_allow_fields) || in_array($_k, $exists_field) && in_array($_k, $unique_fields) || !in_array($_k, $this->banfie))
                    continue;
                $all_field[$_k] = $_v;
            }
            $this->assign("all_field", $all_field);
            $this->assign("modelinfo", $model);
            $this->assign("formid", $this->formid);
            $this->display();
        }
    }

    /**
     * 验证字段是否重复 AJAX
     */
    public function public_checkfield() {
        //新字段名称
        $field    = $this->_get("field");
        //原来字段名
        $oldfield = $this->_get("oldfield");
        if ($field == $oldfield) {
            $this->ajaxReturn($field, "字段没有重复！", true);
        }
        //模型ID
        $modelid = $this->_get("modelid");

        $status = $this->modelfield->where(array("field"   => $field, "modelid" => $modelid))->count();
        if ($status == 0) {
            $this->ajaxReturn($field, "字段没有重复！", true);
        } else {
            $this->ajaxReturn($field, "字段有重复！", false);
        }
    }

    /**
     * 字段属性配置
     */
    public function public_field_setting() {
        //字段类型
        $fieldtype    = $this->_get("fieldtype");
        $fiepath      = $this->fields . $fieldtype . "/";
        //载入对应字段配置文件 config.inc.php 
        require($fiepath . "config.inc.php");
        ob_start();
        include $fiepath . "field_add_form.inc.php";
        $data_setting = ob_get_contents();
        ob_end_clean();
        $settings     = array('field_basic_table'    => $field_basic_table, 'field_minlength'      => $field_minlength, 'field_maxlength'      => $field_maxlength, 'field_allow_search'   => $field_allow_search, 'field_allow_fulltext' => $field_allow_fulltext, 'field_allow_isunique' => $field_allow_isunique, 'setting'              => $data_setting);
        echo json_encode($settings);
        return true;
    }

    /**
     * 字段的启用与禁用 
     */
    public function disabled() {
        $fieldid  = intval($_GET['fieldid']);
        $disabled = $_GET['disabled'] ? 0 : 1;
        $status   = $this->modelfield->where(array('fieldid' => $fieldid))->save(array('disabled' => $disabled));
        if ($status !== false) {
            $this->success("操作成功！");
        } else {
            $this->error("操作失败！");
        }
    }

}

/**
 * 代码加亮
 * @param String  $str 要高亮显示的字符串 或者 文件名
 * @param Boolean $show 是否输出
 * @return String
 */
function highlight_code($str, $show = false) {
    if (file_exists($str)) {
        $str = file_get_contents($str);
    }
    $str = stripslashes(trim($str));
    // The highlight string function encodes and highlights
    // brackets so we need them to start raw
    $str = str_replace(array('&lt;', '&gt;'), array('<', '>'), $str);

    // Replace any existing PHP tags to temporary markers so they don't accidentally
    // break the string out of PHP, and thus, thwart the highlighting.

    $str = str_replace(array('&lt;?php', '?&gt;', '\\'), array('phptagopen', 'phptagclose', 'backslashtmp'), $str);

    // The highlight_string function requires that the text be surrounded
    // by PHP tags.  Since we don't know if A) the submitted text has PHP tags,
    // or B) whether the PHP tags enclose the entire string, we will add our
    // own PHP tags around the string along with some markers to make replacement easier later

    $str = '<?php //tempstart' . "\n" . $str . '//tempend ?>'; // <?
    // All the magic happens here, baby!
    $str = highlight_string($str, TRUE);

    // Prior to PHP 5, the highlight function used icky font tags
    // so we'll replace them with span tags.
    if (abs(phpversion()) < 5) {
        $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
        $str = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
    }

    // Remove our artificially added PHP
    $str = preg_replace("#\<code\>.+?//tempstart\<br />\</span\>#is", "<code>\n", $str);
    $str = preg_replace("#\<code\>.+?//tempstart\<br />#is", "<code>\n", $str);
    $str = preg_replace("#//tempend.+#is", "</span>\n</code>", $str);

    // Replace our markers back to PHP tags.
    $str = str_replace(array('phptagopen', 'phptagclose', 'backslashtmp'), array('&lt;?php', '?&gt;', '\\'), $str); //<?
    $line   = explode("<br />", rtrim(ltrim($str, '<code>'), '</code>'));
    $result = '<div class="code"><ol>';
    foreach ($line as $key => $val) {
        $result .= '<li>' . $val . '</li>';
    }
    $result .= '</ol></div>';
    $result = str_replace("\n", "", $result);
    if ($show !== false) {
        echo($result);
    } else {
        return $result;
    }
}

?>
